package com.tuda.system.service.impl;


import com.alibaba.fastjson.JSON;
import com.tuda.common.core.domain.R;
import com.tuda.common.utils.EntityConvertUtils;
import com.tuda.common.utils.ToolUtil;
import com.tuda.system.model.param.UserRegParam;
import com.tuda.system.model.result.LoginUserResult;
import com.tuda.system.model.wx.AppUserWXParam;
import com.tuda.system.service.ITudaVerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.tuda.system.mapper.TudaAppletUserMapper;
import com.tuda.system.domain.TudaAppletUser;
import com.tuda.system.service.ITudaAppletUserService;

import javax.annotation.Resource;

/**
 * 小程序用户Service业务层处理
 * 
 * @author tuda
 * @date 2023-07-13
 */
@Service
public class TudaAppletUserServiceImpl implements ITudaAppletUserService 
{

    private static final Logger logger = LoggerFactory.getLogger(TudaAppletUserServiceImpl.class);
    @Resource
    private TudaAppletUserMapper tudaAppletUserMapper;
    @Resource
    private ITudaVerificationCodeService verificationCodeService;

    /**
     * 查询小程序用户
     * 
     * @param params 登录信息
     * @return 小程序用户
     */
    public R<LoginUserResult> selectTudaAppletUserByPhone(UserRegParam params)
    {
        //校验验证码
        if (!verificationCodeService.checkCode(params.getPhone(), 1, params.getCode())) {
            return R.fail("验证码错误，请重新输入");
        }
        LoginUserResult result;
        //校验手机号是否被注册
        TudaAppletUser user = tudaAppletUserMapper.selectTudaAppletUserByPhone(params.getPhone());
        if (ToolUtil.isNotEmpty(user)) {
            result = EntityConvertUtils.convertAToB(user, LoginUserResult.class);
            return R.ok(result);
        }
        user = new TudaAppletUser();
        user.setNickName("驾驶员");
        user.setUserType(3);
        user.setPhone(params.getPhone());
        tudaAppletUserMapper.insertTudaAppletUser(user);
        result = EntityConvertUtils.convertAToB(user, LoginUserResult.class);
        return R.ok(result);
    }



    /**
     * 微信登录，比对unionId/openid，如果为空则创新用户
     *
     * @param param 微信登录参数
     * @return 微信在平台的用户
     */
    public TudaAppletUser loginWeChat(AppUserWXParam param) {
        logger.info(JSON.toJSONString(param) + "-------UserWXParam!-------");
        TudaAppletUser user = tudaAppletUserMapper.queryUserByWxUnionId(param.getUnionId());
        if (ToolUtil.isNotEmpty(user)) {
            user.setWxOpenId(param.getWxMiniOpenId());
            user.setWxUnionId(param.getUnionId());
            tudaAppletUserMapper.updateTudaAppletUser(user);
            return user;
        } else {
            user = new TudaAppletUser();
            user.setWxOpenId(param.getWxMiniOpenId());
            user.setWxUnionId(param.getUnionId());
            user.setNickName(param.getWxName());
            tudaAppletUserMapper.insertTudaAppletUser(user);
        }
        return user;
    }
}
